package com.appleyk.config;

import com.appleyk.util.SnCustomDictWordUtils;
import com.appleyk.util.SnFileUtils;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.List;

/**
 * <p>全局配启动 -- 初始化项目时，执行命令，将相关额外的自定义词典加载下</p>
 *
 * @author Appleyk
 * @version v1.0.0
 * @blob https://blog.csdn.net/Appleyk
 * @date created on 21:25 2020/3/31
 */
@Component
public class SnCommandRunner implements CommandLineRunner {

    @Value("${HanLP.CustomDictionary.path.frameworkDict}")
    private String frameworkDictPath;

    @Value("${HanLP.CustomDictionary.cache.path}")
    private String cacheDictPath;

    @Override
    public void run(String... args){
        //先删除缓存
        File file = new File(cacheDictPath);
        if(file.exists()){
            file.delete();
            System.out.println("CustomDictionary.txt.bin delete success .");
        }
        /**加载自定义的【技术框架】字典,注意文件的编码一定要是utf8 == 设置词性 kj 0*/
        loadDict(frameworkDictPath,0);
    }

    /**
     * 加载自定义词性字典
     * @param path 字典路径
     * @param type 类型
     */
    public void loadDict(String path,Integer type) {
        File file = SnFileUtils.getFile(path);
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(file));
            addCustomDictionary(br, type);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 添加自定义分词及其词性，注意数字0表示频率，不能没有
     *
     * @param br 字节流（读）
     * @param type 字典类型
     */
    public void addCustomDictionary(BufferedReader br, int type) {
        String word;
        try {
            while ((word = br.readLine()) != null) {
                switch (type) {
                    /**设置技术框架名称的词性 == kj 0*/
                    case 0:
                        /**对应英文的处理，全部转小写*/
                        word = word.toLowerCase();
                        SnCustomDictWordUtils.setNatureAndFrequency(word,"kj 0",true);
                        break;
                    default:
                        break;
                }
            }
            br.close();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
